package com.wrupple.muba.catalogs.client.activity.process.impl;

import com.google.gwt.event.shared.EventBus;
import com.google.inject.Provider;
import com.wrupple.muba.catalogs.client.activity.process.CatalogEditingProcess;
import com.wrupple.muba.catalogs.client.activity.process.EditionActivityProcess;
import com.wrupple.muba.catalogs.client.activity.process.state.BrowsePlaceInterpret;
import com.wrupple.muba.catalogs.client.activity.process.state.ContentLoadingState;
import com.wrupple.muba.catalogs.client.activity.process.state.InteractionExitState;
import com.wrupple.muba.catalogs.client.activity.process.state.VoidInteractionExitState;
import com.wrupple.muba.catalogs.domain.CatalogBrowsePlace;
import com.wrupple.muba.catalogs.domain.CatalogDetailPlace;
import com.wrupple.muba.catalogs.domain.CatalogEntry;
import com.wrupple.muba.catalogs.domain.JsCatalogKey;
import com.wrupple.muba.common.client.activity.ActivityProcessImpl;
import com.wrupple.muba.common.domain.DesktopPlace;
import com.wrupple.muba.common.shared.State;
import com.wrupple.muba.common.shared.StateTransition;


public class EditionActivityProcessImpl extends ActivityProcessImpl implements EditionActivityProcess{
	
	protected CatalogEditingProcess<?> editingProcess;

	public EditionActivityProcessImpl(BrowsePlaceInterpret read,ContentLoadingState load,CatalogEditingProcess<?> process,InteractionExitState finalState) {
		super();
		addState(read);
		this.editingProcess = process;
		addState(load);
		for(State<?,?> s : process){
			add(s);
		}
		addState(finalState);
		finalState.setCatalogIdProvider(read.getCatalogIdProvider());
	}


	/*
	 * 
	 * ALTERNATIVE EXIT SCENARIOS
	 */

	public static class ExitToDetailActivityImpl implements InteractionExitState {

		private Provider<String> provider;

		@Override
		public void setCatalogIdProvider(Provider<String> p) {
			this.provider = p;
		}

		@Override
		public void start(CatalogEntry parameter,
				StateTransition<DesktopPlace> onDone, EventBus bus) {
			String catalog = provider.get();
			String id = parameter.getIdAsString();
			if(id==null){
				JsCatalogKey key = parameter.cast();
				id = key.getId();
			}
			onDone.setResultAndFinish(new CatalogDetailPlace(catalog,id ));
		}

	}

	
	public static class ExitToBrowseActivity  implements VoidInteractionExitState {

		private Provider<String> provider;

		@Override
		public void setCatalogIdProvider(Provider<String> p) {
			this.provider = p;
		}

		@Override
		public void start(CatalogEntry parameter,
				StateTransition<DesktopPlace> onDone, EventBus bus) {
			
			onDone.setResultAndFinish(new CatalogBrowsePlace(provider.get()));
		}

	}
	
	@Override
	public void setContext(com.wrupple.muba.common.shared.State.Context context) {
		editingProcess.setContext(context);
		super.setContext(context);
	}

}
